<?php

declare(strict_types=1);

namespace App\Resource\Service;

use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Model\GoodsUnitModel;

class GoodsUnitService extends BaseService
{
    /**
     * @param array $where
     * @param int $perPage
     * @param array|string[] $field
     *
     * @return array
     */
    public function getList(array $where, int $perPage = 15, array $field = ['*'])
    {
        $query = GoodsUnitModel::query();
        !empty($where['title']) && $query->whereRaw('INSTR(title, ?) > 0', [$where['title']]);
        $list = $query->paginate($perPage, $field);
        if ($list) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $list];
        }
        return ['code' => ErrorCode::SERVER_ERROR];
    }

    /**
     * @param int $id
     *
     * @return array
     */
    public function getInfoById(int $id)
    {
        $res = GoodsUnitModel::query()->where('id', $id)->select('id', 'title')->first();
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res];
        }
        return ['code' => ErrorCode::NOT_EXIST];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function add(array $params)
    {
        $res = GoodsUnitModel::create(['title' => $params['title']]);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $res -> id]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param array $params
     *
     * @return array
     */
    public function update(array $params)
    {
        if (!$params['id']) {
            return ['code' => ErrorCode::PARAMS_INVALID];
        }
        $res = GoodsUnitModel::where(['id' => $params['id']])->update(['title' => $params['title']]);
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $params['id']]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }

    /**
     * @param int $id
     *
     * @return mixed
     */
    public function delete(int $id)
    {
        $res = GoodsUnitModel::where('id', $id)->delete();
        if ($res) {
            return ['code' => ErrorCode::SUCCESS, 'data' => $res, 'info' => ['target_id' => $id]];
        }
        return ['code' => ErrorCode::NOT_IN_FORCE];
    }
}
